/*
 * @lc app=leetcode.cn id=817 lang=typescript
 *
 * [817] 链表组件
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function numComponents(head: ListNode | null, nums: number[]): number {
  const numsSet = new Set<number>([...nums]);
  // 是否是组件头
  let isHead = false;
  let ans = 0;
  while (head) {
    if (numsSet.has(head.val)) {
      if (!isHead) {
        isHead = true;
        ans++;
      }
    } else {
      isHead = false;
    }
    head = head.next;
  }

  return ans;
}
// @lc code=end
